package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import com.qianfan.invoice.service.InvoiceOcrService;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
public class InvoiceTest {

    @Autowired
    private InvoiceOcrService invoiceOcrTemplate;

    // 定义一个接口正常检测 get请求 返回一个字符串 无参数
    @GetMapping("/api/invoice/test")
    public ResponseEntity<?> invoiceOcr() {
        return ResponseEntity.ok("接口正常");
    }

    @GetMapping("/api/invoice/ocr")
    public ResponseEntity<?> recognizeInvoice() {
        try {
            // 2. 读取图片文件并转换为Base64
            File imageFile = new File("D:\\java_project\\ocr\\demo\\src\\main\\resources\\fptest2.jpeg");
            byte[] imageBytes = Files.readAllBytes(imageFile.toPath());
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);


           Object result = invoiceOcrTemplate.recognizeInvoice(base64Image);

            return ResponseEntity.ok(result);
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("文件处理失败：" + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("发票识别处理失败：" + e.getMessage());
        }
    }
}
